/**
 * @author wangj881
 * @date 2024-11-21 11:22
 */
public class L707_2 {

    public static void main(String[] args) {
        MyLinkedList obj = new MyLinkedList();
//        int param_1 = obj.get(index);
//        obj.addAtHead(val);
//        obj.addAtTail(val);
//        obj.addAtIndex(index, val);
//        obj.deleteAtIndex(index);
    }


    static class MyLinkedList {
        private int val;
        private ListNode next;
        int size;

        public MyLinkedList() {
            size = 0;
            next = new ListNode(0);

        }

        public int get(int index) {
            if (index < 0 || index >= size) {
                return -1;
            }
            ListNode head = this.next;
            for (int i = 0; i <= index; i++) {
                head = head.next;
            }
            return head.val;
        }

        public void addAtHead(int val) {
            ListNode listNode = new ListNode(val);
            listNode.next = next.next;
            this.next = listNode;
            size++;
        }

        public void addAtTail(int val) {
            ListNode listNode = new ListNode(val);
            ListNode head = this.next;
            while (head.next != null) {
                head = head.next;
            }
            head.next = listNode;
            size++;
        }

        public void addAtIndex(int index, int val) {
            if (index > size) {
                return;
            }
            size++;
            if (index <= 0) {
                addAtHead(val);
            }
            ListNode listNode = new ListNode(val);
            ListNode node = getNode(index);
            if (node != null) {
                if (node.next != null) {
                    listNode.next = node.next;
                }
                node.next = listNode;
            }
        }

        public void deleteAtIndex(int index) {
            if (index < 0 || index >= size) {
                return;
            }
            size--;
            ListNode node = getNode(index);
            if (node != null) {
                if (node.next != null) {
                    node.next = node.next.next;
                }
                node.next = null;
            }

        }

        public ListNode getNode(int index) {
            if (index < 1) {
                return null;
            }
            ListNode head = this.next;
            for (int i = 0; i < index; i++) {
                if (head.next == null) {
                    return null;
                }
                head = head.next;
            }
            return head;

        }


    }
}
